package com.kitty.game.gm;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.admin.service.AdminService;
import com.kitty.game.child.model.ChildInfo;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.gm.handler.*;
import com.kitty.game.gm.handler100.*;
import com.kitty.game.gm.handler1000.AdminGmFather;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.AccountLogin;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.utils.FieldUtils;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.RoleNameChangeEvent;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.web.client.GmCloseAi;
import com.kitty.web.client.GmCreateAi;
import com.kitty.web.client.GmLoginAi;
import com.kitty.web.client.GmMoveAi;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;




@Service
public class GmService {
    /**
     * 超级管理员
     */
    HashMap<String, AdminGmFather> gm1000 = new HashMap();
    /**
     * gm管理员
     */
    HashMap<String, GMFather> gm200 = new HashMap();
    /**
     * 内测
     */
    HashMap<String, NCGmFather> gm100 = new HashMap();

    public void init() {
        gm200.put("@@@closeai", new GmCloseAi());
        gm200.put("@@@createai", new GmCreateAi());
        gm200.put("@@@loginai", new GmLoginAi());
        gm200.put("@@@moveai", new GmMoveAi());

        gm200.put("@@@check", new GmRoleInfo());
        gm200.put("@@@查看所有信息", new GmRoleInfo());

        gm200.put("@@@online", new GmOnline());
        gm200.put("@@@查看在线人数", new GmOnline());

        gm200.put("@@@fenbi", new GmFenbi());
        gm200.put("@@@封闭角色", new GmFenbi());

        gm200.put("@@@jinyan", new GmJinyan());
        gm200.put("@@@禁言角色", new GmJinyan());

        gm200.put("@@@gonggao", new GmGonggao());
        gm200.put("@@@发送公告", new GmGonggao());

        gm200.put("@@@unlock",new GmUnlock());
        gm200.put("@@@解除安全锁",new GmUnlock());

        gm200.put("@@@jifenAll",new GmJifenAll());
        gm200.put("@@@补偿所有人积分",new GmJifenAll());

        gm200.put("@@@choujiangAll",new GmChoujiangAll());
        gm200.put("@@@补偿所有人抽奖",new GmChoujiangAll());

        gm200.put("@@@yinyuanbaoAll",new GmYinyuanbaoAll());
        gm200.put("@@@补偿所有人银元宝",new GmYinyuanbaoAll());

        gm200.put("@@@jinyuanbaoAll",new GmJinyuanbaoAll());
        gm200.put("@@@补偿所有人金元宝",new GmJinyuanbaoAll());

        gm200.put("@@@notice",new GmNotice());
        gm200.put("@@@修改公告", new GmNotice());

        gm200.put("@@@发送道具",new GmSendDaoju());

        gm200.put("@@@name",new GmName());


        gm200.put("@@@rechargeRank", new GmChargeRank());    // 开启充值排行榜活动   @@@rechargeRank==20201214##1  活动1/活动2/活动3
        gm200.put("@@@startShidao", new GmShidao());    //0关,1开




        gm200.put("@@@level",new GmLevel());



        gm200.put("@@@jiefenbi",new GmFenbiOpen());
        gm200.put("@@@quitTeam",new GmQuitTeam());
        gm200.put("@@@mail",new GmMail());







        //玩家退出战斗
        gm200.put("@@@quitMY",new GmQuitFight());
        gm200.put("@@@bangpai",new GmBangpai());

        gm200.put("@@@subDaohang",new GmDaohangDown());
        gm200.put("@@@rate",new GmChargeRate());
        gm200.put("@@@choujiangRank",new GmChoujiangRank());

        // 开启圣诞节充值活动命令 0关,1开
        //       gm200.put("@@@shengdanjiechongzhi",new GmChongzhiShengdanjie());*/

        // 100内测权限
        gm100.put("@fabao", new NCFabao());
        gm100.put("@chongzhi", new NCChongzhi());
        gm100.put("@jinbi", new NCJinbi());
        gm100.put("@money", new NCJinbi());
        gm100.put("@exp", new NCExp());
        gm100.put("@pot", new NCQianneng());
        gm100.put("@qianneng", new NCQianneng());
        gm100.put("@matiral", new NCWuxue());
        gm100.put("@wuxue", new NCWuxue());
        gm100.put("@gold", new NCGold());
        gm100.put("@jinyuanbao", new NCGold());
        gm100.put("@shuxin", new NCShuxing());
        gm100.put("@pet", new NCPet());
        gm100.put("@jifen", new NCJifen());
        gm100.put("@qimen", new NCMiJingJiFei());
        gm100.put("@haoxin", new NCHaoXinZhi());
        gm100.put("@choujiang", new NCChoujiang());
        gm100.put("@yinde", new NCYinde());
        gm100.put("@equip", new NCEquip());
        gm100.put("@banggong", new NCBanggong());
        gm100.put("@daohang", new NCDaohang());
        gm100.put("@zhuangbei", new NCZhuangbei());
        gm100.put("@shoushi", new NCShoushi());
        gm100.put("@shoushiX5",new NCShoushiX5());

        gm100.put("@wupin", new NCWupin());
    }

    public String getRoleInfo(Role role, Account account, AccountLogin accountLogin) {
        long hour = (role.getLockTime() - System.currentTimeMillis()) / TimeUtil.ONE_HOUR;
        if (hour <= 0) {
            hour = 0;
        }
        long jinyan = (role.getLockTime() - System.currentTimeMillis()) / TimeUtil.ONE_HOUR;
        if (jinyan <= 0) {
            jinyan = 0;
        }
        String notice = "账号=#R" + account.getUsername() + "#n"
                + " 注册码=#R" + accountLogin.getChannelCode() + "#n"
                + "角色名称=#R" + role.getName() + "#n"
                + "角色ID=#R" + role.getRoleId() + "#n"
                + "帮派名称=#R" + role.getPartyName() + "#n"
                + "帮派ID=#R" + role.getPartyId() + "#n"
//                + " 金币=#R" + role.getMoney() + "#n"
                + " 五行金币=#R" + role.getWuxingBankMoney() + "#n"
//                + " 银元宝=#R" + role.getSiver() + "#n"
                + " 金元宝=#R" + account.getGold() + "#n"
//                + " 珍宝元宝=#R" + role.getStallGold() + "#n"
//                + " 珍宝元宝=#R" + role.getStallGold() + "#n"
                + " 累计积分=#R" + role.getTotalCharge() + "#n"
                + " 封号时长=#R" + hour + "小时#n"
                + " 禁言时长=#R" + jinyan + "小时#n"
                + " 当前剩余积分=#R" + role.getActivity().getRechargeScore() + "#n!";
        return notice;
    }

    public void level(Role role, int level) {
        /*判断人物和元婴等级*/
        if (level > (role.isRealBody() ? 179 : 179)) {
            return;
        }
        ChildInfo childInfo = role.getChildInfo();
        int currlevel = role.isRealBody() ? role.getLevel() : childInfo.getLevel();
        if (currlevel >= level) {
            return;
        }
        RoleService roleService = SpringUtils.getRoleService();
        for (int i = currlevel; i < level; i++) {
            long needExp = 0;
            needExp = role.isRealBody() ? roleService.getRoleUpgradeNeedExp(role.getLevel()) : childInfo.getUpgradeExp();
            SpringUtils.getRoleService().addExp(role, (int) (needExp + 100), role.getLevel(), role.getPetBox().getFightPetId());
        }
        if (role.isRealBody()) {
            role.setLevel((short) level);
        } else {
            childInfo.setLevel((short) level);
        }

        List<FiedValue> values = FieldUtils.rolePanelInfo(role);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(values);
        MessagePusher.pushMessage(role, respUpdate);

        Pet pet = role.getPetBox().getPetByPetId(role.getPetBox().getFightPetId());
        if (pet != null) {
            pet.setLevel((short) (Math.min(level, 125)));
            SpringUtils.getPetService().refreshPetInfo(role, pet);
        }
    }

    public String replaceName(String content) {
        if (content.contains("{") && content.contains("}")) {
            content = content.replace("{", "");
            content = content.replace("}", "");
            content = content.trim();
            String[] strings = content.split("=");
            content = strings[0].trim();
        }
        return content.trim();
    }

//    public void check(Role aaaaa,String name,boolean boo){
//        name = replaceName(name);
//        Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
//        if (role == null){
//            long uid = getUidByName(name);
//            role = SpringUtils.getRoleService().getPlayerBy(uid);
//            if (role == null){
//                MessagePusher.pushMessage(aaaaa,new RespNotifyMiscEx("角色不存在"));
//                return;
//            }
//        }
//        Account account = SpringUtils.getAccountService().getAccount(role.getSid());
//        if (account == null){
//            MessagePusher.pushMessage(aaaaa,new RespNotifyMiscEx("没有账号"));
//            return;
//        }
//
////        String notice = "账号=#R" + account.getUsername() + "#n"
////                + " 注册码=#R" + account.getChannelCode() + "#n"
////                + "角色名称=#R" + role.getName() + "#n"
////                + "角色ID=#R" + role.getRoleId() + "#n"
//////                + " 金币=#R" + role.getMoney() + "#n"
//////                + " 银元宝=#R" + role.getSiver() + "#n"
////                + " 金元宝=#R" + account.getGold() + "#n"
//////                + " 珍宝元宝=#R" + role.getStallGold() + "#n"
////                + " 累计积分=#R" + role.getTotalCharge() + "#n"
////                + " 当前剩余积分=#R" + role.getActivity().getRechargeScore() + "#n"
////                + " 封号时长=#R" + hour + "小时#n"
////                + " 禁言时长=#R" + jinyan + "小时#n"
////                + "";
//        MessagePusher.pushMessage(aaaaa, new RespNotifyMiscEx( getRoleInfo(role, account, accountLogin)));
//    }

    public long getUidByName(String name) {
        String sqlstr = "select uid from t_role where name=@name";
        Sql sql = Sqls.create(sqlstr);
        sql.setParam("name", name);
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection connection, ResultSet resultSet, Sql sql) throws SQLException {
                if (resultSet.next()) {
                    return resultSet.getLong("uid");
                }
                return 0;
            }
        });
        SpringUtils.getBean(Dao.class).execute(sql);
        long uid = sql.getLong();
        return uid;
    }

    public void jinyan(Role aaa, String content) {
        String[] strings = content.split("##");
        String name = strings[0];
        name = replaceName(name);
        String boo = strings[1];
        Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
        if (role == null) {
            long uid = getUidByName(name);
            role = SpringUtils.getRoleService().getPlayerBy(uid);
            if (role == null) {
                MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("角色不存在"));
                return;
            }
        }
        AdminService adminService = SpringUtils.getBean(AdminService.class);
        if (boo.equals("1")) {
            adminService.shutChannel(role, System.currentTimeMillis() + 90 * TimeUtil.ONE_DAY);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你已经被禁言！"));
        } else {
            adminService.shutChannel(role, 0);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你的禁言已经解开，可以发言！"));
            MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("禁言已经解开"));
        }
    }

    public void fenbi(Role aaa, String content) {
        String[] strings = content.split("##");
        String name = strings[0];
        name = replaceName(name);
        String boo = strings[1];
        Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
        if (role == null) {
            long uid = getUidByName(name);
            role = SpringUtils.getRoleService().getPlayerBy(uid);
            if (role == null) {
                MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("角色不存在"));
                return;
            }
        }
        long uid = role.getUid();
        AdminService adminService = SpringUtils.getBean(AdminService.class);
        if (boo.equals("1")) {
            adminService.blockPlayer(role, System.currentTimeMillis() + 90 * TimeUtil.ONE_DAY);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你已被封禁!"));
            ServerService serverService = SpringUtils.getBean(ServerService.class);
            serverService.getScheduledExecutorService().schedule(new Runnable() {
                @Override
                public void run() {
                    IoSession session = SessionUtils.getSessionBy(uid);
                    if (session != null) {
                        session.closeNow();
                    }
                }
            }, 3, TimeUnit.SECONDS);
        } else {
            adminService.blockPlayer(role, 0);
            MessagePusher.pushMessage(aaa, new RespNotifyMiscEx("封闭已经解开"));
        }
    }

    public void name(Role aaa, String content) {
        content = replaceName(content);
        content = content.trim();
        String[] strings = content.split("##");
        Role temp = SpringUtils.getBean(Dao.class).fetch(Role.class, Cnd.where("roleId", "=", Integer.parseInt(strings[0])));
        if (temp == null) {
            return;
        }
        temp.doAfterInit();
        // 内存中是否有这个角色
        Role role = SpringUtils.getPlayerService().getPlayerBy(temp.getUid());
        if (role != null) {
            temp = role;
        }
        String oldName = temp.getName();
//        Set<String> nameList = temp.getExtendBox().getNameList();
//        nameList.add(oldName);
        temp.setName(strings[1]);
        temp.save();
        // 让玩家重上
        SpringUtils.getPlayerService().updateRoleName(oldName, temp);
//        SpringUtils.getRoleService().modifyName(temp, strings[1]);
        EventDispatcher.getInstance().fireEvent(new RoleNameChangeEvent(EventType.ROLE_NAME_CHANGE, temp, oldName, strings[1]));

        IoSession session = SessionUtils.getSessionBy(temp.getUid());
        if (session != null) {
            session.closeNow();
        }
    }

    public HashMap<String, GMFather> getGm200() {
        return gm200;
    }

    public HashMap<String, AdminGmFather> getGm1000() {
        return gm1000;
    }

    public HashMap<String, NCGmFather> getGm100() {
        return gm100;
    }
}
